package com.cyj.dream.auth.listener;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cyj.dream.auth.entity.SysUser;
import com.cyj.dream.auth.persistence.service.ITbSysUserService;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 用户excel导入监听器
 * @BelongsProject: DreamChardonnay
 * @BelongsPackage: com.cyj.dream.auth.listener
 * @Author: ChenYongJia
 * @CreateTime: 2021-10-12 09:05
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Slf4j
@NoArgsConstructor
public class SysUserExcelListener extends AnalysisEventListener<SysUser> {

    private ITbSysUserService iTbSysUserService;

    /**
     * 需要保存的数据列表
     */
    private List<SysUser> saveList = new ArrayList();

    /**
     * 需要修改的数据列表
     */
    private List<SysUser> updateList = new ArrayList();

    /**
     * 每个00条记录批量存储一次数据
     */
    private static final int BATCH_COUNT = 100;

    /**
     * 构造函数
     *
     * @param iTbSysUserService
     */
    public SysUserExcelListener(ITbSysUserService iTbSysUserService) {
        this.iTbSysUserService = iTbSysUserService;
    }

    /**
     * 导入的执行处理逻辑
     *
     * @param sysUser         用户实体类
     * @param analysisContext 分析上下文
     * @return
     * @author ChenYongJia
     * @date 2021/10/12
     */
    @Override
    public void invoke(SysUser data, AnalysisContext analysisContext) {
        data.setDelFlag(0);
        data.setCreateTime(LocalDateTime.now());
        // 用户昵称和手机号不为空执行
        if (!StrUtil.isEmpty(data.getUsername()) && !StrUtil.isEmpty(data.getSysUserPhone())) {
            LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUser::getUsername, data.getUsername());
            queryWrapper.eq(SysUser::getSysUserPhone, data.getSysUserPhone());
            SysUser sysUser = iTbSysUserService.getOne(queryWrapper);
            // 若是数据库中已存在该用户信息则直接进行修改操作，否则就直接新增
            if (!ObjectUtils.isEmpty(sysUser)) {
                data.setDreamId(sysUser.getDreamId());
                this.updateList.add(data);
                if (this.updateList.size() >= BATCH_COUNT) {
                    updateData();
                    //保存完成清除addList数据，防止内存移除
                    this.updateList.clear();
                }
            } else {
                this.saveList.add(data);
                if (this.saveList.size() >= BATCH_COUNT) {
                    saveData();
                    //保存完成清除addList数据，防止内存移除
                    this.saveList.clear();
                }
            }
        }
    }

    /**
     * 数据解析完成执行入库操作
     *
     * @param context 解析出的上下文内容
     * @return
     * @author ChenYongJia
     * @date 2021/10/12
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //当最后剩余的数据记录数不足BATCH_COUNT时，我们最终一次性存储剩余数据
        if (saveList.size() >= 1) {
            saveData();
        }
        if (updateList.size() >= 1) {
            updateData();
        }
        log.info("所有数据解析完成！");
    }

    /**
     * 批量保存
     */
    private void saveData() {
        try {
            if (saveList.size() > 0) {
                iTbSysUserService.saveBatch(saveList);
            }
        } catch (Exception e) {
            log.info("批量保存到数据库失败，错误信息为：{}", e);
        }
    }

    /**
     * 批量修改数据到数据库
     */
    private void updateData() {
        try {
            if (updateList.size() > 0) {
                iTbSysUserService.saveOrUpdateBatch(updateList);
            }
        } catch (Exception e) {
            log.info("批量修改数据到数据库失败，错误信息为：{}", e);
        }
    }

}
